import { GenerateService, ISelectParamForm } from '@manycore/pages-vm-api';
import { ApiImpl } from 'message-lite';
import {
  doorCategoryId,
  formulaNumber3VariableReplace,
  getSelectedElements,
  modelFilter,
  transformParamToData,
  unique,
} from '../../util';
import {
  defaultFormula,
  defaultGenerateField,
  defaultPositionFormula,
  defaultProductId,
  defaultRotationFormula,
} from '../../constant';
import { CustomModel } from '../../types';

@ApiImpl()
export class GenerateServiceImpl extends GenerateService {
  /**
   * 获取默认参数时指定的数据
   */
  async getGenerateFormFields() {
    const product = (await IDP.Custom.Design.CustomModel.newCustomModelByProductIdAsync(
      defaultProductId
    )) as CustomModel;

    return defaultGenerateField.map((item) => {
      return {
        groupName: item.groupName,
        fields: item.fields.map((key) => {
          const param = product.getParam(key)!;
          return transformParamToData([param]);
        }),
      };
    });
  }

  /**
   * 生成中间件模型
   * @param form
   */
  async generate(form: { form: ISelectParamForm[] }): Promise<void> {
    const selected = getSelectedElements().map((i) => i.id);
    const option = IDP.Custom.DoorCoveringHardware.getOption();
    if (!selected.length) {
      return;
    }
    const models = (await Promise.all(
      selected.map((id) => IDP.Custom.Design.CustomModel.getCustomModelByModelIdAsync(id))
    )) as CustomModel[];

    const centerProduct = (await IDP.Custom.Design.CustomModel.newCustomModelByProductIdAsync(
      defaultProductId
    )) as CustomModel;

    const allDoor = modelFilter(
      unique(
        models.map((i) => i.getRoot(true)),
        (i) => i.id
      ),
      (item) => {
        // 直接选中掩门
        if (option.selectTarget === 'door') {
          return selected.includes(item.id);
        } else {
          // 掩门，并且掩门没有插件中间件
          return (
            item.category === doorCategoryId && !item.getChild().filter((i) => i.productId === defaultProductId).length
          );
        }
      },
      6
    );
    const allField = form.form.map((i) => i.fields).flat(1);
    allDoor.forEach((door) => {
      const productClone = centerProduct.clone();
      door.appendChild(productClone);
      // 设置旋转及位置公式

      productClone.setPositionFormula(formulaNumber3VariableReplace(defaultPositionFormula, door));
      productClone.setRotationFormula(formulaNumber3VariableReplace(defaultRotationFormula, door));
      // 设置所有的默认公式
      defaultFormula.forEach((formula) => {
        productClone.getParam(formula[0])?.setFormula(typeof formula[1] === 'function' ? formula[1](door) : formula[1]);
      });
      // 针对表单字段，设置对应每个字段值
      allField.forEach((field) => {
        let value = field.value;
        if (typeof field.value !== 'undefined') {
          const v = typeof value === 'string' ? value : (value ?? '').toString();
          value = !isNaN(parseFloat(v)) ? parseFloat(v) : value;
        }
        if (typeof value !== 'undefined') {
          productClone.getParam(field.name)?.setValue(value);
        }
      });
    });
    await IDP.Custom.Design.CustomModel.updateAsync({
      models: unique(allDoor.map((i) => i.getRoot(true))),
    });
    // 触发更新展示
    IDP.Custom.DoorCoveringHardware.setOption(IDP.Custom.DoorCoveringHardware.getOption()!);
  }
}
